package net.pugsplace.gpremacy.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Logger;

import net.pugsplace.gpremacy.packets.Depart;
import net.pugsplace.gpremacy.packets.Packet;
import net.pugsplace.gpremacy.rules.RuleSet;
import net.pugsplace.gpremacy.server.net.Connection;
import net.pugsplace.gpremacy.state.GameState;

public class Game implements ClientListener {
	private static Logger log = Logger.getLogger(Game.class.getName());
	/** Synchronized collection of all connections in this game */
	private final Collection<Connection> connnections;
	private RuleSet rules;
	private GameState state;
	private final String name;

	public Game(String n) {
		name = n;
		connnections = Collections.synchronizedCollection(new ArrayList<Connection>());
	}

	public void addClientConnection(Connection client) {
		// TODO: Update the client with the current game state
		this.connnections.add(client);
	}

	public void clientDisconnected(Connection connectionObject) {
		connnections.remove(connectionObject);
	}

	public Collection<Connection> getAllConnnections() {
		return connnections;
	}

	public String getName() {
		return name;
	}

	public RuleSet getRules() {
		return rules;
	}

	public GameState getState() {
		return state;
	}

	public boolean receivedPacket(Connection connectionObject, Packet packetObject) {

		// Let the rules try and handle the packet
		// Explicit synchronization
		synchronized (rules) {
			if (rules.receivedPacket(connectionObject, packetObject)) {
				return true;
			}
		}

		// Okay, check if it's a depart packet
		if (packetObject instanceof Depart) {
			connnections.remove(packetObject);
			return true;
		}

		// We can't handle it
		return false;
	}

}
